<?php

namespace app\logic;

use app\models\Item;
use app\models\Role;
use app\models\User;
use app\forms\ItemForm;
use app\models\UserItem;
use app\models\RoleItem;
use yii\web\HttpException;
use app\components\helpers\TreeHelper;
use app\components\helpers\MappingHelper;

/**
 * 权限项逻辑类
 */
class ItemLogic extends BaseLogic
{
    /**
     * 权限项首页
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function index($param)
    {
        $form = self::_validateForm($param, 'index');
        $itemTop = Item::getTopList();
        $itemArr = Item::getListWithUserAndRoleCount($form['parentId']);
        $pidArr = array_column($itemArr, 'parentId');
        sort($pidArr);
        $item = TreeHelper::format($itemArr, $pidArr[0]);
        return ['item' => $item, 'itemTop' => $itemTop];
    }

    /**
     * 创建权限项
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = self::_validateForm($param, 'create');
        $attr = $form->getAttributes();
        $attr['parent_id'] = $attr['parentId'];
        $attr['data_auth'] = $attr['dataAuth'];
        Item::newCreate($attr);
        throw new HttpException(200, 'OK');
    }

    /**
     * 编辑权限项
     * @param $param
     * @throws HttpException
     */
    public static function update($param)
    {
        $form = self::_validateForm($param, 'update');
        $attr = $form->getAttributes();
        $attr['data_auth'] = $attr['dataAuth'];
        unset($attr['parentId'], $attr['id'], $attr['dataAuth']);
        Item::updateByPk($attr, $form['id']);
        throw new HttpException(200, 'OK');
    }

    /**
     * 删除权限项
     * @param $param
     * @throws HttpException
     * @throws \Throwable
     */
    public static function delete($param)
    {
        $form = self::_validateForm($param, 'delete');
        $model = Item::findOne($form['id']);
        if ($model->getChildrenCount() > 0) {
            throw new HttpException(423);
        }
        $model->performDelete();
        throw new HttpException(200, 'OK');
    }

    /**
     * 禁用、启用
     * @param $param
     * @throws HttpException
     */
    public static function status($param)
    {
        $form = self::_validateForm($param, 'status');
        $model = Item::findOne($form['id']);
        $model->status = $form['status'];
        $model->save(false);
        $model->setChildrenStatus($form['status']);
        throw new HttpException(200);
    }

    /**
     * 下拉列表
     * @return array
     */
    public static function getDropList()
    {
        return ['item' => Item::getDropList()];
    }

    /**
     * 角色、用户、岗位 权限
     * @return mixed
     */
    public static function getTreeList()
    {
        $item = Item::getListForAuth();
        $arr['item'] = TreeHelper::format($item);
        $arr['typeList'] = MappingHelper::dataAuthList();
        $arr['authList'] = MappingHelper::fieldAuthList();
        return $arr;
    }

    /**
     * 用户列表
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getUser($param)
    {
        $form = self::_validateForm($param, 'get-user');
        return User::getListByItemId($form);
    }

    /**
     * 角色列表
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getRole($param)
    {
        $form = self::_validateForm($param, 'get-role');
        return Role::getListByItemId($form);
    }

    /**
     * 移除角色
     * @param $param
     * @throws HttpException
     */
    public static function removeRole($param)
    {
        $form = self::_validateForm($param, 'remove-role');
        RoleItem::deleteAll(['and', ['item_id' => $form['id']], ['in', 'role_id', $form['roleId']]]);
    }

    /**
     * 移除用户
     * @param $param
     * @throws HttpException
     */
    public static function removeUser($param)
    {
        $form = self::_validateForm($param, 'remove-user');
        UserItem::deleteAll(['and', ['item_id' => $form['id']], ['in', 'user_id', $form['userId']]]);
    }

    /**
     * 参数、表单数据 验证
     * @param $param
     * @param $scenario
     * @return ItemForm
     * @throws HttpException
     */
    public static function _validateForm($param, $scenario)
    {
        $form = new ItemForm();
        $form->setScenario($scenario);
        $form->setAttributes($param);
        if (!$form->validate()) {
            throw new HttpException(400, $form->getFirstError());
        }
        return $form;
    }

    /**
     * Notes:获取所有权限项
     * Date: 2020/7/27
     * Time: 16:11
     * @return array|false
     */
    public static function _getItem()
    {
        $itemArr = Item::getList([
            'select' => [
                'id',
                'name',
                'parent_id AS parentId',
                'data_auth AS auth',
                '(0) AS type',
                '(0) AS checked',
                'status'
            ]
        ]);
        return array_combine(array_column($itemArr, 'id'), array_values($itemArr));
    }

}